/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.applis.demo.actions;

import opiam.admin.applis.demo.beans.Person;

import opiam.admin.faare.MessageUtil;
import opiam.admin.faare.service.services.SortService;
import opiam.admin.faare.struts.actions.SecureAction;
import opiam.admin.faare.struts.utils.SessionContext;

import org.apache.log4j.Logger;

import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.List;


/**
 * This class allows to add users to or remove users from the temporary list.
 */
public class SelectCancelFromCartAction extends SecureAction
{
    /** Logger de log4j */
    private static Logger _logger =
        Logger.getLogger(SelectCancelFromCartAction.class);

    /**
     * This method is called to execute the action once the checks have been
     * performed by the SecureAction class.
     *
     * @param mapping              Struts mapping data.
     * @param actionForm           FormBean associated with the action.
     * @param request              HTTP request.
     * @param httpServletResponse  HTTP response.
     *
     * @return An ActionForward.
     *
     * @throws IOException  An I/O exception if failed or interrupted I/O operations occurs.
     * @throws ServletException  A ServletException if the servlet has a problem.
     */
    @Override
	public org.apache.struts.action.ActionForward secureExecute(org.apache.struts.action.ActionMapping mapping,
                                                                org.apache.struts.action.ActionForm actionForm,
                                                                javax.servlet.http.HttpServletRequest request,
                                                                javax.servlet.http.HttpServletResponse httpServletResponse
                                                               )
        throws java.io.IOException, javax.servlet.ServletException
    {
        String cartname = request.getParameter("cartname");
        String[] elements = request.getParameterValues("eltindex");

        if (elements == null)
        {
            // aucune selection
            request.setAttribute("cartname", cartname);

            return (mapping.findForward("success"));
        }

        _logger.debug("cartname = " + cartname);

        ActionMessages errors = new ActionMessages();

        if ((cartname == null) || cartname.trim().equals(""))
        {
            _logger.error(MessageUtil.getMessageString("MSG_ARGUMENT_NULL"));
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                       new ActionMessage("error.service.unknown")
                      );
            saveErrors(request, errors);

            return (mapping.findForward("service_error"));
        }

        try
        {
            HttpSession session = request.getSession();
            String usersListName = "selectedUsers";
            ArrayList usersList = new ArrayList();

            List currentCart = (List) session.getAttribute(cartname);

            for (int i = 0; i < elements.length; i++)
            {
                Person user =
                    (Person) currentCart.get(Integer.parseInt(elements[i]));
                usersList.add(user);
            }

            // Sorts the list
            SortService.sort(usersList, Person.class, "name",
                             SessionContext.getInstance(session).getUserContext()
                            );

            // Returns the list 
            request.setAttribute("cartname", cartname);
            request.setAttribute("eltindex", elements);
            session.setAttribute(usersListName, usersList);

            return (mapping.findForward("success"));
        }
        catch (Exception se)
        {
            _logger.error(se.getMessage());
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                       new ActionMessage("error.service.unknown")
                      );
            saveErrors(request, errors);

            return (mapping.findForward("service_error"));
        }
    }
}
